import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/postjson")
public class PostJsonServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       resp.setContentType("text/html;charset=utf-8");
       //1.得到数据流
        ServletInputStream inputStream = req.getInputStream();
        //2.使用数组接收数据流
        byte[] bytes=new byte[req.getContentLength()];
        inputStream.read(bytes);
        //3.将数组转换为字符串
        String str=new String(bytes,"utf-8");
        ObjectMapper objectMapper=new ObjectMapper();
        //把json字符串转化为对象
        User user=objectMapper.readValue(str,User.class);
        System.out.println("用户名："+user.getUsername()+" "+"密码:"+user.getPassword());
        resp.getWriter().println("用户名："+user.getUsername()+" "+"密码:"+user.getPassword());

    }
}

@Setter
@Getter
@ToString
class User{
    private String username;
    private String password;
}
